<template>
  <div class="common-layout">
    <el-form class="header" ref="queryRef" :inline="true">

      <el-form-item label="组号" prop="group">
        <el-input clearable v-model="groupNum"
                  style="width: 200px;"
                  @blur="inputKeyUpEvent"
                  placeholder="请输入组号(1-89)"></el-input>
      </el-form-item>

      <el-form-item>
        <el-button
            type="primary"
            style="width:100px;"
            @click="searchByUnit">查询
        </el-button>

        <el-button
            type="success"
            @click="submitRecordStudy"
            style="width:100px;margin-left: 20px"
        >
          提交记录
        </el-button>

        <div class="time-display">
          {{ formattedTime }}
        </div>

        <el-button
            plain
            type="primary"
            :disabled="isRunning || (isCountdown && initialTime === 0 && currentTime === 0)"
            @click="startTimer"
        >
          {{
            isCountdown && currentTime === 0 && initialTime > 0 && !isRunning ? '开始' : (isRunning ? '运行中' : '启动')
          }}
        </el-button>

        <el-button
            plain
            type="warning"
            :disabled="!isRunning"
            @click="pauseTimer"
        >
          暂停
        </el-button>

        <el-button
            plain
            :disabled="isRunning"
            @click="resetTimer"
        >
          重置
        </el-button>

        <el-button
            v-if="false"
            type="warning"
            @click="addFilterBlur"
            style="width:100px;margin-left: 20px"
        >
          {{ hiddenAllStatus ? '隐藏选项' : '显示选项' }}
        </el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="20" class="grid-row">
      <el-col v-for="(item, index) in questionsData"
              :key="index" style="margin-top: 5px">
        <el-card shadow="hover">
          <div style="padding: 8px;">
            <strong> {{ index + 1 }}.</strong>
            <span style="font-size: 20px;color: #409EFF;font-weight: bold">{{ item.name }}</span>
            <span style="color: purple;font-size: 12px">{{ item.type }}</span>
            <span @click="buttonClick(item)" style="color: blue;float: right;cursor: pointer">发音</span>
            <div style="margin-top: 10px;display: flex;flex-direction: column;gap: 8px">
              <button
                  v-for="(opt, idx) in item.options"
                  :key="idx"
                  class="option"
                  :class="{
                    hiddenAll: item.enabled,
                    selected: userAnswers[item.id] === opt,
                    correct: showResult && opt === item.chinese,
                    wrong: showResult && userAnswers[item.id] === opt && opt !== item.chinese
                  }"
                  @click="selectOption(item.id, opt)"
                  :disabled="showResult"
              >
                {{ opt }}
              </button>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 结果显示 -->
    <div v-if="showResult" class="result">
      <h4>
        答对 {{ questionsData.filter(q => userAnswers[q.id] === q.chinese).length }} / {{ total }} 题
      </h4>
      <p :style="{ color: accuracy >= 80 ? '#52c41a' : accuracy >= 60 ? '#faad14' : '#f5222d' }">
        正确率：{{ correctRate }}%
      </p>
    </div>
  </div>
</template>

<script setup>
import {getPageUnitTimes, handleColumnAudio, insertDataToNewRecord} from "@/api/word/index.js";
import {getCurrentInstance, ref} from 'vue'
import {parseTime} from "@/utils/ruoyi.js";
import {addStudy_record, addWordTest, getUsedTime} from "@/api/word/wordRecord.js";
import {isPartialEqual, shuffleArray, shuffleArrayLength} from "@/api/utils/index.js";
import {useTimerStore} from "@/store/timer.js";
import '@/assets/styles/word-common.css'
import {isNumberStr} from "@/utils/index.js";
import {getListData} from "@/api/cet4/index.js";

let time_value = ref(Date.now())

const {proxy} = getCurrentInstance();

//初始化题目+选项-new
const showResult = ref(false)
const hiddenAllStatus = ref(true)
const questionsData = ref([])
let groupNum = ref(Math.ceil(Math.random() * 89))
const testWord = ref({})
const userAnswers = ref({}) // 用户选择
const userTime = ref({})   // 用户点击时间
const correctNum = ref(0)
const correctRate = ref('')
const recordSubmit = ref({})
const testWordNum = ref({})
const testWordType = ref({})
let recordFrom = ref({})

//时间
const timerStore = useTimerStore();
// 从 store 中解构 actions
timerStore.isCountdown = false;
const {startTimer, pauseTimer, resetTimer, setInitialTime} = timerStore;
// 从 store 中解构 state 和 getters (保持响应性)
const {formattedTime, isRunning, isCountdown, initialTime, currentTime} = storeToRefs(timerStore); // 添加 currentTime

let pageData = ref([])

let total = ref(0)
let wordClicked = ref(0)
let practiceId = ref(null)

initPage()

async function initPage() {
  // await loadAnotherWord()
  await handleQueryTimes()
  practiceId.value = Math.random().toString().substring(2)
  // addFilterBlur()
}

function inputKeyUpEvent() {
  if (groupNum.value === '') {
    return
  }
  if (!isNumberStr(groupNum.value) || groupNum.value % 1 !== 0) {
    proxy.$modal.msgWarning("组号必须为整数")
    return
  }
  if (groupNum.value > 89 || groupNum.value < 1) {
    proxy.$modal.msgWarning("组号必须在1-89之间")
    return
  }
  handleQueryTimes()
}


function submitRecordStudy() {
  if (correctNum.value === 0) {
    proxy.$modal.msgWarning("学习的记录为空")
    return
  }
  if (correctNum.value !== 50) {
    proxy.$modal.msgWarning("还有未学习的单词")
    return
  }

  proxy.$modal.confirm('是否确认提交').then(function () {
    pauseTimer() //完成学习时，停止计时器

    recordFrom.value.wordNum = total.value
    recordFrom.value.practice = practiceId.value
    recordFrom.value.complete = groupNum.value

    recordFrom.value.usedTime = formattedTime.value
    recordFrom.value.correctNum = correctNum.value
    recordFrom.value.correctRate = correctNum.value / total.value
    // console.log(recordFrom.value)
    handleInsertRecordData(recordFrom.value)
  }).catch(() => {
    proxy.$modal.msg("取消提交")
  })
}

//发音以及附加功能
function buttonClick(item) {
  // deleteFilterBlur(item)
  handleColumnAudio(item)
}

//连接MYSQL数据库-插入数据
function handleInsertRecordData(data) {
  // console.log(data)
  data.type = 'cet4'
  addStudy_record(data).then(res => {
    // console.log(res)
    recordFrom.value = {}
    if (res.code === 200) {
      // testResultWindowData(wordClicked.value)
      practiceId.value = Math.random().toString().substring(2)
      // proxy.$modal.msgSuccess("提交成功")
      wordClicked.value = 0
    }
  })
}

async function searchByUnit() {
  correctNum.value = 0
  proxy.$modal.msg("查询的组号:" + groupNum.value)
  await handleQueryTimes()
  // console.log(total.value)
  time_value.value = Date.now() + 1000 * total.value * 6
  resetTimer()
  // addFilterBlur()
  // console.log(total.value)
}

async function handleQueryTimes() {
  testWordNum.value = {}
  testWordType.value = {}
  testWord.value = []
  await getListData(groupNum.value).then((res) => {
    if (res.code === 200 && res.data !== undefined) {
      pageData.value = shuffleArray(res.data)
      total.value = res.data.length
    }
  })

  pageData.value.forEach(item => {
    testWord.value[item.name] = item.chinese
  })
  initQuestions()
}

function randomData() {
  pageData.value = shuffleArray(pageData.value)
}

//隐藏选项功能
function addFilterBlur() {
  let value = questionsData.value;
  // console.log(value)
  value.forEach((item) => {
    item.enabled = true
  })
}

const initQuestions = () => {
  const wordList = Object.keys(testWord.value)
  // console.log(wordList)
  const list = []
  // console.log(anotherData.value)
  for (let i = 0; i < total.value; i++) {
    const name = wordList[i]
    let element = testWord.value[name];

    // 匹配规则：
    // 1. 匹配所有字母 (a-zA-Z)
    // 2. 匹配单个点，但该点前后都不是点（使用负向环视）
    let optionAll = element.toString().trim().replace(/[a-zA-Z&]|(?<!\.)\.(?!\.)/g, "");
    // console.log(optionAll)
    let s = optionAll.substring(optionAll.indexOf(".") + 1);
    let split = s.split(" ");

    // console.log(split);
    let temp = split[Math.floor(Math.random() * split.length)];

    while (temp === "" || temp === "(" || temp === ")") {
      temp = split[Math.floor(Math.random() * split.length)];
    }
    // console.log(temp)

    let chinese = temp.replace(/=/g,"");
    // getSimilarData(type)
    const distractors = generateDistractors(chinese, [])
    const options = shuffle([chinese, ...distractors])

    list.push({
      id: `q${i + 1}`,
      name,
      options,
      chinese
    })
  }
  questionsData.value = list
  // console.log(pageData.value)

  userAnswers.value = {}
  userTime.value = {}
  showResult.value = false
}

// 选择选项
const selectOption = (qid, option) => {
  userAnswers.value[qid] = option
  userTime.value[qid] = parseTime(new Date())
  correctNum.value++
  startTimer()
}

// 打乱数组
const shuffle = (arr) => {
  const a = [...arr]
  for (let i = a.length - 1; i > 0; i--) {
    const j = Math.floor(Math.random() * (i + 1))
    ;[a[i], a[j]] = [a[j], a[i]]
  }
  return a
}

// 生成干扰项（3个错误选项）
const generateDistractors = (correct, all) => {
  return shuffle(all.filter(w => w !== correct)).slice(0, 3)
}

</script>

<style scoped lang="scss">

:deep(.el-radio__label) {
  font-size: 32px;
  line-height: 2;
}

.header {
  margin-top: 20px;
  margin-left: 20px;
}

.option:hover:not(.selected):not(:disabled) {
  background: #91d5ff;
  color: white;
}

.options {
  flex-wrap: wrap;
  gap: 10px; /* 项目间距 */
}

/* Grid布局实现5列 */
.grid-row {
  padding: 0 20px;
  display: grid;
  grid-template-columns: repeat(5, 1fr); /* 5列，每列平均分配 */
  gap: 5px; /* 列之间的间距 */
}

.option {
  display: flex;
  padding: 8px 12px;
  background: #f0f8ff;
  border: 1px solid #91d5ff;
  border-radius: 6px;
  cursor: pointer;
  font-size: 14px;
  transition: all 0.2s;
}

.option.selected {
  background: #52c41a;
  color: white;
  border-color: #52c41a;
}

.option:disabled {
  cursor: not-allowed;
  opacity: 0.8;
}

:deep(.el-radio__label) {
  font-size: 32px;
  line-height: 2;
}

.actions {
  text-align: center;
  margin: 20px 0;
}

.btn-submit {
  padding: 10px 24px;
  background: #67C23A;
  color: white;
  border: none;
  border-radius: 6px;
  font-size: 16px;
  cursor: pointer;
}

.btn-submit:hover {
  background: #40a9ff;
}

.result {
  text-align: center;
  margin-top: 20px;
  font-weight: bold;
  font-size: 1.2em;
}

.option.hiddenAll {
  filter: blur(8px);
}
</style>
